import React, { useEffect, useState } from 'react'
import styles from './index.module.less'
import { Button, Dialog, Toast } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'


interface user {
  icon: string,
  nickname: string,
  username: string,
}

export default function UserInfo() {

  const navigate = useNavigate()

  const localInfo = JSON.parse(localStorage.getItem('userInfo') as string)

  // 用户信息
  const [userInfo] = useState(localInfo)
  // token
  const token = localStorage.getItem('token')
  // 登录
  const loginBtnClick = () => {
    navigate('/my/login')
  }

  // 进入更新用户信息界面
  const gotoUpdateInfo = () => {

    if (token) {
      navigate('/my/updateuserinfo')
    } else {
      isLogin()
    }
  }

  // 登录提示
  const isLogin = () => {
    if (!token) {
      Dialog.confirm({
        title: '登录提示',
        content: '暂未登录,是否立即登录',
        onConfirm: () => {
          navigate('/my/login')
        },
        onCancel: () => {
          Toast.show({
            content: '你取消了登录',
            duration: 1000
          })
        }
      })
    }
  }

  // 进入用户注册页面
  const registerBtnClick = () => {
    navigate('/my/register')
  }

  useEffect(() => {
    isLogin()
  }, [])
  return (
    <div>
      <div className={styles.infoBox} onClick={gotoUpdateInfo}>

        <div className={styles.imgBox}>
          {
            userInfo ? <img src={userInfo.icon} alt="" className={styles.tx} /> : null
          }
        </div>

        <div className={styles.userInfo}>
          <div className={styles.nickname}>
            {userInfo ?
              <span className={styles.nickname}>{userInfo.nickname}</span> :
              <span>Hi~</span>
            }
          </div>
          <div className={styles.userId}>
            {userInfo ?
              <span>用户名:{userInfo.username}</span> :
              <span>您还没有登录呢</span>
            }
          </div>
        </div>
      </div>

      {
        token ? null :
          <div className={styles.login}>
            <Button color='primary' fill='outline' className={styles.loginBtn} onClick={registerBtnClick}>注册</Button>
            <Button color='primary' className={styles.loginBtn} onClick={loginBtnClick}>登录</Button>
          </div>
      }
    </div>
  )
}
